package no.ntnu.fp.server;

import java.io.EOFException;
import java.io.IOException;

import no.ntnu.fp.net.co.Connection;

public class ConnectionThread extends Thread {
	private Connection connection;
	private ServerThread masterThread;
	
	public ConnectionThread( ServerThread serverThread, Connection connection ){
		super( connection.getLocalAddress() );
		this.connection = connection;
		masterThread = serverThread;
		setDaemon(true);
		setPriority(Thread.NORM_PRIORITY);
		start();
	}
	
	/**
	 * Loop and listen for packets. EOFException happens when connection is closed.
	 */
	public void run() {
		boolean closeConnection = false;
		
		//While there is a open connection, listen to packets
		while( !closeConnection ) {
			try {
				String message = connection.receive();
				//Console.printConsole("Message recieved from " + connection.getRemoteAddress() + ": " + message);
				
				String answer = masterThread.translateMessage(message);
				connection.send(answer);
			} catch (EOFException e) {
				try {
					connection.close();
					closeConnection = true;
				}
				catch( IOException ex ) {
					Console.printError("Could not close connection with " + connection.getRemoteAddress() + " - " + e);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		//Tell the server that the client has disconnected
		masterThread.disconnectClient(this);
	}

	
}
